package com.jack.common.dubbo.filter;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Objects;
import java.util.Set;

public class ValidationUtils {
    private static ValidatorFactory factory = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory();

    public static <T> void validate(T t) {
        if (Objects.isNull(t)) {
            throw new RuntimeException("param empty");
        }
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        if (null != constraintViolations && constraintViolations.size() > 0) {
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                throw new RuntimeException(constraintViolation.getMessage());
            }
        }
    }
}
